<?php
/**
 * Note:
 * Date: 2021/12/30
 */
namespace App\Http\Controllers\Admin;

use App\Caches\Game\AppWebpageCache;
use App\Models\Game\Center\AppWebpage;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AppWebpageController extends CurdController
{
    protected string $classModel = AppWebpage::class;

    protected array $searchFields = [
        'type' => self::FIELD_TYPE_NORMAL,
        'name' => self::FIELD_TYPE_LIKE,
        'is_default' => self::FIELD_TYPE_NUMERIC,
        'sources' => self::FIELD_TYPE_JSON_CONTAINS_NUMERIC,
    ];

    protected array $orderFields = [
        'type' => 'ASC',
        'is_default' => 'DESC',
    ];

    /**
     * 保存之前校验
     * @param Request $request
     */
    public function storeBefore(Request $request)
    {
        $rule = [
            'type' => "required|string",
            'name' => "required|string",
            'path' => [
                'required',
                Rule::unique("gameCenter.{$this->model->getTable()}")->where('type', $request->type),
            ],
            'sources' => 'sometimes|array',
        ];
        // 一个类型只能有一个默认,
        if ($request->is_default) {
            $rule['is_default'] = [
                Rule::unique("gameCenter.{$this->model->getTable()}")->where('type', $request->type),
            ];
        }
        $request->validate($rule, [
            'is_default.unique' => '该类型已存在默认页面',
        ]);
    }

    /**
     * 更新之前校验
     * @param Request $request
     */
    public function updateBefore(Request $request)
    {
        $rule = [
            'type' => "required|string",
            'name' => "required|string",
            'path' => [
                'required',
                Rule::unique("gameCenter.{$this->model->getTable()}")->where('type', $request->type)->ignore($request->id),
            ],
            'sources' => 'sometimes|array',
        ];
        // 一个类型只能有一个默认,
        if ($request->is_default) {
            $rule['is_default'] = [
                Rule::unique("gameCenter.{$this->model->getTable()}")->where('type', $request->type)->ignore($request->id),
            ];
        }
        $request->validate($rule, [
            'is_default.unique' => '该类型已存在默认页面',
        ]);
    }

    /**
     * @param AppWebpage $appWebpage
     * @param Request $request
     * @return void
     */
    public function storeAfter(AppWebpage $appWebpage, Request $request)
    {
        $this->syncSources($appWebpage);
    }

    /**
     * @param AppWebpage $appWebpage
     * @param Request $request
     * @return void
     */
    public function updateAfter(AppWebpage $appWebpage, Request $request)
    {
        $this->syncSources($appWebpage);
    }

    /**
     * 一个渠道只能关联一个页面, 将其他页面关联的渠道去除
     * @param AppWebpage $appWebpage
     * @return void
     */
    private function syncSources(AppWebpage $appWebpage)
    {
        AppWebpageCache::reset();
    }
}
